package com.spx.core.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeSelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;

import com.spx.core.CoreActivator;
import com.spx.core.types.Activity;
import com.spx.core.types.Role;

public class DeleteActionFromRoleHandler extends AbstractHandler
{

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException
	{
		final IStructuredSelection selection = getSelection(event);

		// Get the Role in question

		for (final Object object : selection.toArray())
		{
			if (object instanceof Activity)
			{

				final Role parent;
				if (selection instanceof ITreeSelection)
				{
					final ITreeSelection treeSelection = (ITreeSelection) selection;
					final TreePath[] path = treeSelection.getPathsFor(treeSelection.getFirstElement());
					final TreePath parentPath = path[path.length - 1].getParentPath();
					if (parentPath.getFirstSegment() instanceof Role)
					{
						parent = (Role) parentPath.getFirstSegment();
						final Shell shell = HandlerUtil.getActiveWorkbenchWindow(event).getShell();
						final Activity activity = (Activity) object;
						final boolean doDelete = MessageDialog.openQuestion(shell, "Confirm  Deletion", "Really Delete Activity: " + activity.getName());
						if (doDelete)
						{

							CoreActivator.getDefault().getSecurityService().deleteActionFromRole(activity, parent);
						}
					}
				}
			}

		}

		return null;
	}

	private IStructuredSelection getSelection(ExecutionEvent event)
	{
		final IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getCurrentSelection(event);
		return selection;
	}
}
